package com.example.innospace.demos.web.controller;


import com.example.innospace.demos.pojo.dto.StudentDTO;
import com.example.innospace.demos.pojo.dto.StudentPasswordUpdateDTO;
import com.example.innospace.demos.pojo.entity.Project;
import com.example.innospace.demos.pojo.entity.Student;
import com.example.innospace.demos.pojo.entity.Teacher;
import com.example.innospace.demos.pojo.enums.MessageEnum;
import com.example.innospace.demos.pojo.enums.ResponseCodeEnum;
import com.example.innospace.demos.pojo.result.R;
import com.example.innospace.demos.pojo.vo.StudentVO;
import com.example.innospace.demos.pojo.vo.StudentWithProject;
import com.example.innospace.demos.utils.JWTUtils;
import com.example.innospace.demos.utils.OssUtil;
import com.example.innospace.demos.web.mapper.TeacherMapper;
import com.example.innospace.demos.web.service.ProjectService;
import com.example.innospace.demos.web.service.StudentService;
import com.example.innospace.demos.web.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生端
 * TODO 学生密码没有按学号来，admin那边有
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private OssUtil ossUtil;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    /**
     * 学生用户登录//根据学号登录
     * @param studentDto
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request,@RequestBody StudentDTO studentDto)
    {

        //查询用户
        Student student=studentService.findById(studentDto.getStudentId());
        if(student==null)
        {
            return R.error(ResponseCodeEnum.BAD_REQUEST, MessageEnum.DATA_NOT_FOUND);
        }
        //查询到了
        //判断密码是否正确
        //loginUser对象中的password是密文
        if(studentDto.getPassword().equals(student.getPassword()))
        {

            //登录成功
            request.getSession().setAttribute("studentId",student.getStudentId());
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",student.getStudentId());
            claims.put("username",student.getName());
            //登录成功以后，从登录用户中获得id，获得用户名字，通过JwtUtil来获得这样一个（用户）字段下的Token令牌
            String token= JWTUtils.genToken(claims);
            return R.success(ResponseCodeEnum.SUCCESS,token,MessageEnum.OPERATION_SUCCESS);//将令牌传出
        }
        return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PASSWORD_ERROR);
    }


    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //1.清除session中的用户id
        request.getSession().removeAttribute("studentId");
        //2.返回结果
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.LOGOUT_SUCCESS);
        //3.页面会跳转回登录界面

    }

    /**
     * 修改学生个人信息
     * 不包含头像的更新
     * @param student
     * @return
     */
    @PutMapping
    public R update(@RequestBody Student student)
    {
        boolean update=studentService.update(student);
        if(update)
        {
            return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
        }
        else
        {
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.OPERATION_FAILED);
        }

    }


    /**
     * 上传头像接口
     * @return
     */
    @PostMapping("/student/uploadAvatar")
    public R<String> upload(@RequestParam String studentId, @RequestParam("file") MultipartFile file) throws IOException { // 上传文件到 OSS
        String fileUrl = ossUtil.uploadFile(file);
        // 将文件 URL 存储到数据库（这里需要调用 Service 层）
        studentService.updateAvatar(studentId, fileUrl);
        return R.success(ResponseCodeEnum.SUCCESS,fileUrl,MessageEnum.OPERATION_SUCCESS);

    }
    /**
     * 下载头像接口
     *
     * @return
     */
    @GetMapping("/student/getAvatar")
    public R<String> getAvatar(@RequestParam String studentId) {
        // 从数据库获取头像文件的 URL（这里需要调用 Service 层）
         String fileUrl = studentService.getAvatar(studentId);

        // 返回文件的 URL
        return R.success(ResponseCodeEnum.SUCCESS,fileUrl,MessageEnum.UPLOAD_SUCCESS);
    }



    /**
     * // 学生信息回显接口
     * @param studentId
     * @return
     */
    @GetMapping("/student/info")
    public R<StudentVO> getStudentInfo(@RequestParam String studentId) {
        Student student=studentService.getStudentInfo(studentId);
        StudentVO studentVO=new StudentVO();
        BeanUtils.copyProperties(student,studentVO);
        return R.success(ResponseCodeEnum.SUCCESS,studentVO,MessageEnum.OPERATION_SUCCESS);
    }

    /*
     *修改学生密码接口
     * @param dto
     * @return
     */
    @PutMapping("/student/password")
    public R updatePassword(@RequestBody StudentPasswordUpdateDTO dto) {
        String studentId = dto.getStudentId();
        String oldPassword = dto.getOldPassword();
        String newPassword = dto.getNewPassword();

        String password = studentService.getpassword(studentId);
        if (password.equals(oldPassword)) {
            studentService.updatePassword(newPassword, studentId);
            return R.success(ResponseCodeEnum.SUCCESS, MessageEnum.OPERATION_SUCCESS);
        }
        return R.error(ResponseCodeEnum.BAD_REQUEST, MessageEnum.PASSWORD_ERROR);
    }

    /**
     * 查询所参与的项目
     * @param studentId
     * @return
     */
    @GetMapping("/projects/byStudentId")
    public R<StudentWithProject> getProjectsByStudentId(@RequestParam String studentId) {
        StudentWithProject studentWithProject=new StudentWithProject();
        //获得这名学生的信息
        Student student=studentService.findById(studentId);
        if (student == null) {
            // 处理学生不存在的情况，例如返回错误信息
            return R.error(ResponseCodeEnum.BAD_REQUEST, null);
        }
        //获得这个学生所属项目的信息
        Project project=new Project();
        Integer projectId=student.getProjectid();
        project=projectService.getById(projectId);
        if (project != null) {
            // 处理项目不存在的情况，例如返回错误信息
            //将项目信息保存进项目
            studentWithProject.setProject(project);
            String leader=project.getStudentId();
            //添加队长
            if (studentId.equals(leader)) {
                // 如果是队长
                studentWithProject.setStudent(studentService.findById(studentId));
                // 将队员的加入
                List<Student> students = studentService.findByProjectId(project.getId());
                if (students != null) {
                    // 移除队长
                    students.removeIf(student1 -> student1.getStudentId().equals(leader));
                    if(!students.isEmpty())
                    studentWithProject.setStudents(students);
                }
            }
            else
            {
                //如果不是队长

                //加入队长的
                studentWithProject.setStudent(studentService.findById(project.getStudentId()));
                //将队员的加入
                //将队员的加入
                List<Student> students=new ArrayList<>();
                students=studentService.findByProjectId(project.getId());
                if(students!=null)
                {
                    studentWithProject.setStudents(students);
                }
            }
            //加入老师
            //第一知道老师

            String first_teacher= project.getFirstTeacher();
            if(first_teacher!=null)
            {
                Teacher teacher=new Teacher();
                teacher=teacherService.findById(first_teacher);
                if (teacher != null) {
                    studentWithProject.setFirst_teacher(teacher);
                }
                studentWithProject.setFirst_teacher(teacher);
            }
            //第一知道老师
            String second_teacher=project.getSecondTeacher();
            if(second_teacher!=null)
            {
                Teacher teacher=new Teacher();
                teacher=teacherService.findById(second_teacher);
                if (teacher != null) {
                    studentWithProject.setFirst_teacher(teacher);
                }
                studentWithProject.setFirst_teacher(teacher);
            }
        }
        return R.success(ResponseCodeEnum.SUCCESS,studentWithProject,MessageEnum.OPERATION_SUCCESS);
    }
}
